<?php

namespace app\api\middleware;

use app\common\repositories\users\UsersRepository;
use support\Container;
use Webman\MiddlewareInterface;
use Webman\Http\Request;
use Webman\Http\Response;
use support\Db;

class TokenAuthMiddleware implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {
        
        $token = get_token();

        if (empty($token)) {
            return json(['code' => 410, 'msg' => 'Unauthorized: No token provided'], 410);
        }

        $user = Container::make(UsersRepository::class)->getOneUserByToken($token);

        if (empty($user)) {
            return json(['code' => 410, 'msg' => 'Unauthorized: Invalid token'], 410);
        }
        // Attach user information to the request
        $request->user = $user;
        $request->token = $token;
        
        return $next($request);
    }
}
